<template>
  <view class="container">
        <view class="top-safe-height" :style="{ height: topSafeHeight + 'px' }"></view>

    <!-- 头部 -->
    <view class="header">
      <view class="nav-header">
        <text class="iconfont icon-arrow-alt" @tap="goBack"></text>
        <text class="title">{{ inOrOutWarehouseTypeText }}库单详情</text>
        <text
          class="iconfont icon-scan"
          style="color: #1890ff"
          @tap="handleScan"
          v-if="!isDisabled"
        >
          <span style="font-size: 32rpx; margin-left: 10rpx">扫码入库</span>
        </text>
      </view>
      <!-- 基本信息 -->
      <input type="text" />

      <view class="basic-info">
        <view class="info-row">
          <view class="info-item">
            <text class="label">{{ inOrOutWarehouseTypeText }}库单号：</text>
            <text class="value number">{{ detail.inOrOutOrderNumber }}</text>
            <view
              :class="[
                'status',
                detail.inOrOutWarehouseStatus === 0
                  ? 'pending'
                  : detail.inOrOutWarehouseStatus === 1
                  ? 'completed'
                  : 'cancelled',
              ]"
              >{{ statusText }} </view
            >
          </view>
        </view>
        <view class="info-row">
          <view class="info-item">
            <text class="label">{{ inOrOutWarehouseTypeText }}库类型：</text>
            <text class="value">{{ getOperateTypeText(detail.operateType, detail.inOrOutWarehouseType) }}</text>
          </view>
          <view class="info-item">
            <text class="label">{{ inOrOutWarehouseTypeText }}库仓库：</text>
            <text class="value">{{ getWarehouseName(detail) }}</text>
          </view>
          <view class="info-item">
            <text class="label">备注说明：</text>
            <text class="value">{{ detail.remarks }}</text>
          </view>
        </view>
        <view class="info-row">
          <view class="info-item">
            <text class="label">应{{ inOrOutWarehouseTypeText }}数量：</text>
            <text class="value">{{ detail.totalNumber }}</text>
          </view>
          <view class="info-item">
            <text class="label">实{{ inOrOutWarehouseTypeText }}数量：</text>
            <text class="value">{{  inOrOutWarehouseType == 1 ? detail.actualOutputQuantityTotalNumber : detail.actualQuantityTotalNumber }}</text> 
          </view>
          <view class="info-item">
            <text class="label">创建时间：</text>
            <text class="value">{{ detail.createTime }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="content">
      <view class="table-header">
        <view class="th">序号</view>
        <view class="th">商品编码</view>
        <view class="th">商品名称</view>
        <view class="th">图片</view>
        <view class="th">商品规格</view>
        <view class="th">单位</view>
        <view class="th">应{{ inOrOutWarehouseTypeText }}数量</view>
        <view class="th">实{{ inOrOutWarehouseTypeText }}数量</view>
        <!-- <view class="th">操作</view> -->
      </view>
      <scroll-view
        scroll-y
        class="table-body"
        :scroll-into-view="scrollIntoId"
        scroll-with-animation
      >
        <view
          v-for="(item, index) in goodsList"
          :key="item.itemNumber"
          class="table-row"
          :id="'row-' + index"
          :class="{ highlighted: index === highlightedIndex }"
        >
          <view class="td">{{ index + 1 }}</view>
          <view class="td">{{ item.itemNumber }}</view>
          <view class="td">{{ item.productName }}</view>
          <view class="td">
            <image
              :src="item.image"
              mode="aspectFit"
              class="goods-image"
            ></image>
          </view>
          <view class="td">{{ item.sku }}</view>
          <view class="td">{{ item.unitName }}</view>
          <view class="td">{{ item.number }}</view>
          <view class="td">
            <input
              type="text"
              class="input-field"
              v-model="item.actualQuantity"
              :disabled="isDisabled"
              style="
                border: 1px solid #e8e8e8;
                border-radius: 8rpx;
                padding: 0 4rpx;
              "
            />
          </view>
          <!-- <view class="td">
                        <text class="operate-btn" @tap="handleOperate(item)">货位</text>
                    </view> -->
        </view>
      </scroll-view>
    </view>

    <!-- 底部按钮 -->
    <view class="footer">
      <div class="button-group">
        <button class="cancel-btn" @tap="handleCancel(3)">取消</button>
        <button class="submit-btn" @tap="handleSubmit(2)" v-if="!isDisabled">提交{{inOrOutWarehouseTypeText}}库</button>
      </div>
    </view>
  </view>
</template>

<script>
// import { BarcodeScanner } from "@/utils/scannerUtils.js";
import { saleRoomInfo ,saleRoomOperate} from "@/api";
var statusBarHeight = uni.getSystemInfoSync().statusBarHeight; //手机端头部手机时间位置高度
export default {
  data() {
    return {
      detail:  {},
      goodsList: [],
      inOrOutWarehouseType: 1,
      scanner: null,
      highlightedIndex: -1,
      scrollIntoId: "",
      operateTypeDict: {
        //(1:调拨出入库  2:退货出库 3:采购入库)
        1: {
          1: "调拨出库",
          2: "调拨入库",
        },
        2: "退货出库",
        3: "采购入库",
        4: "销售出库",
        5: "销售退货入库",
      },
      topSafeHeight: statusBarHeight  || 0,
    };
  },
  computed: {
      isDisabled() {
      // 出库单且已出库，或入库单且已入库
      return (
        (this.inOrOutWarehouseType == 1 && this.detail.inOrOutWarehouseStatus == 1) ||
        (this.inOrOutWarehouseType == 2 && this.detail.inOrOutWarehouseStatus == 1)
      );
    },
    statusText() {
      // 0:待出库(待入库) 1:已出库(已入库) 2:已取消
      const statusMap = {
        1: {
          0: "待出库",
          1: "已出库",
          2: "已取消",
        },
        2: {
          0: "待入库",
          1: "已入库",
          2: "已取消",
        },
      };
      return (
        statusMap[this.inOrOutWarehouseType][
          this.detail.inOrOutWarehouseStatus
        ] || "未知状态"
      );
    },
    inOrOutWarehouseTypeText() {
      const typeMap = {
        1: "出",
        2: "入",
      };
      return typeMap[this.inOrOutWarehouseType] || "未知类型";
    },
  },
  onLoad(options) {
	  console.log(options)
    if (options.id) {
      this.loadDetail(options.id);
    }
    if (options.inOrOutWarehouseType) {
      this.inOrOutWarehouseType = options.inOrOutWarehouseType;
    }
    // this.scanner = new BarcodeScanner({
    //   onScan: this.handleScannedProductCode,
    // });
    // this.scanner.init();
    console.log("onLoad");
  },
  onUnload() {
    // this.scanner.destroy();
  },
  methods: {
      getWarehouseName(item=this.detail) {
      if (this.inOrOutWarehouseType == 1) {
        return item.transferOutRoomWarehouseName;
      } else if (this.inOrOutWarehouseType == 2) {
        return item.transferInRoomWarehouseName;
      }
    },
      getOperateTypeText(type, status) {
      if (type === 1) {
        return this.operateTypeDict[type][status] || "未知类型";
      } else  {
        return this.operateTypeDict[type];

      }
      
    },

    updateSubmit(type) {
      if(!this.goodsList.every(item=>item.actualQuantity)){
        uni.showToast({
          title: "请输入实入数量",
          icon: "none",
        });
        return;
      }
       const list = this.goodsList.map(item=>{
        return {
          // ..actualQuantity,
          productAttrValueId:item.productAttrValueId,
          actualQuantity:item.actualQuantity*1
        }
      })
      saleRoomOperate({
          id: this.detail.id,
          operateType: type,
          list:list

        })
        .then((res) => {
          console.log(res);
          if(res.code == 200){
            this.loadDetail(this.detail.id);
          }else{
            uni.showToast({
              title: res.message,
              icon: "none",
            });
          }
        })
        .catch((err) => {
        //   console.log(err);
            uni.showToast({
                title: err,
                icon: "none",
            });
        });
    },
    handleScannedProductCode(code) {
      uni.showToast({
        title: code,
        icon: "none",
      });
      // 先重置scrollIntoId，确保每次都能触发滚动
      this.scrollIntoId = "";

      // 使用nextTick确保重置生效
      this.$nextTick(() => {
        const matchedIndex = this.goodsList.findIndex(
          (item) => item.itemNumber === code
        );
        if (matchedIndex === -1) {
          uni.showToast({
            title: "未找到对应商品",
            icon: "none",
          });
          return;
        }

        // 设置高亮索引
        this.highlightedIndex = matchedIndex;
        // 设置要滚动到的元素id
        this.scrollIntoId = "row-" + matchedIndex;
      });
    },

    goBack() {
      uni.navigateBack();
    },

    loadDetail(number) {
		console.log(number, "555")
      saleRoomInfo({ id: number * 1, limit: 9999 }).then((res) => {
        console.log(res.data);
        this.goodsList = res.data.list;
        this.detail = res.data.inOrOutWarehouseOrders
      }).catch(e=>{
		  console.log(e)
	  });
    },
    handleScan() {
      console.log("扫码入库");
      this.handleScannedProductCode("101641905219");
      // 实现扫码功能
    },
    handleOperate(item) {
      console.log("操作货位", item);
      // 实现货位操作
    },
    handleCancel(type) {
      uni.navigateBack()
      return
      uni.showModal({
        title: "提示",
        content: `确认取消${this.inOrOutWarehouseTypeText}库？`,
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击确定");
            // 实现取消入库
            this.updateSubmit(type)

          }
        },
      });
    },
    handleSubmit(type) {
      uni.showModal({
        title: "提示",
        content: `确认${this.inOrOutWarehouseTypeText}库？`,
        success: (res) => {
          if (res.confirm) {
            console.log("用户点击确定");
            this.updateSubmit(type)
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;

  .header {
    // background-color: #fff;
    background-color: #f5f5f5;
    padding-bottom: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

    .nav-header {
      display: flex;
      align-items: center;
      padding: 40rpx 32rpx 20rpx;
      position: relative;
      border-bottom: 2rpx solid #f0f0f0;
      margin-bottom: 20rpx;

      .iconfont {
        font-size: 40rpx;
        color: #333;
      }

      .title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .scan-btn {
        font-size: 28rpx;
        color: #1890ff;
        background-color: #e6f7ff;
        padding: 8rpx 24rpx;
        border-radius: 28rpx;
      }
    }

    .basic-info {
      padding: 20rpx 32rpx;
      margin: 0 20rpx;
      background-color: #fff;
      border-radius: 12rpx;

      .info-row {
        display: flex;
        align-items: flex-start;
        margin-bottom: 20rpx;

        &:last-child {
          margin-bottom: 0;
        }
      }

      .info-item {
        flex: 1;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        padding: 8rpx 0;

        .label {
          font-size: 28rpx;
          color: #666;
          margin-right: 8rpx;
        }

        .value {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;

          &.number {
            color: #1890ff;
          }
        }

        .status {
          display: inline-block;
          padding: 4rpx 16rpx;
          border-radius: 24rpx;
          font-size: 24rpx;
          font-weight: 500;
          margin-left: 16rpx;

          &.pending {
            color: #ff9900;
            background-color: #fff7e6;
            border: 2rpx solid #ffe7ba;
          }
          &.completed {
            color: #52c41a;
            background-color: #f6ffed;
            border: 2rpx solid #b7eb8f;
          }
          &.cancelled {
            color: #999;
            background-color: #f5f5f5;
            border: 2rpx solid #e8e8e8;
          }
        }
      }
    }
  }

  .content {
    flex: 1;
    background-color: #fff;
    margin: 0 20rpx 120rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;

    .table-header {
      display: flex;
      background-color: #f8f9fa;
      padding: 24rpx 0;
      border-bottom: 2rpx solid #e8e8e8;

      .th {
        flex: 1;
        text-align: center;
        font-size: 26rpx;
        color: #666;
        padding: 0 10rpx;
        font-weight: 500;
      }
    }

    .table-body {
      height: calc(100vh - 600rpx);

      .table-row {
        display: flex;
        padding: 24rpx 0;
        border-bottom: 2rpx solid #f0f0f0;
        transition: background-color 0.3s ease;

        &.highlighted {
          background-color: #e6f7ff !important;
          animation: highlight-pulse 1.5s ease-in-out infinite;
        }

        @keyframes highlight-pulse {
          0% {
            background-color: #e6f7ff;
          }
          50% {
            background-color: #bae7ff;
          }
          100% {
            background-color: #e6f7ff;
          }
        }

        &:hover {
          background-color: #fafafa;
        }

        .td {
          flex: 1;
          text-align: center;
          font-size: 26rpx;
          color: #333;
          padding: 0 10rpx;
          display: flex;
          align-items: center;
          justify-content: center;

          .goods-image {
            width: 80rpx;
            height: 80rpx;
            border-radius: 8rpx;
            border: 2rpx solid #e8e8e8;
          }

          .operate-btn {
            color: #1890ff;
            background-color: #e6f7ff;
            padding: 6rpx 20rpx;
            border-radius: 24rpx;
            font-size: 24rpx;
          }
        }
      }
    }
  }

  .footer {
    position: sticky;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background-color: #fff;
    padding: 24rpx;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
    padding-bottom: calc(constant(safe-area-inset-bottom) + 24rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 24rpx);

    .button-group {
      display: flex;
      align-items: center;
      margin-left: auto;
      padding-right: 32rpx;
      gap: 24rpx;
    }

    button {
      min-width: 180rpx;
      font-size: 28rpx;
      padding: 0 48rpx;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 40rpx;
      font-weight: 500;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &.cancel-btn {
        background-color: #f5f5f5;
        color: #666;
        border: none;

        &:active {
          background-color: #e8e8e8;
          transform: scale(0.98);
        }
      }

      &.submit-btn {
        background: linear-gradient(135deg, #1890ff 0%, #0960bd 100%);
        color: #fff;
        border: none;
        box-shadow: 0 4rpx 12rpx rgba(24, 144, 255, 0.3);

        &:active {
          background: linear-gradient(135deg, #0960bd 0%, #064589 100%);
          transform: scale(0.98);
          box-shadow: 0 2rpx 6rpx rgba(24, 144, 255, 0.2);
        }
      }
    }
  }
}
</style>
